
import { Mastra } from '@mastra/core/mastra';
import { PinoLogger } from '@mastra/loggers';
import { LibSQLStore } from '@mastra/libsql';
import { weatherWorkflow } from './workflows/weather-workflow';
import { weatherAgent } from './agents/weather-agent';
import { investigationWorkflow } from './workflows/investigation.workflow';
import { caseGeneratorAgent } from './agents/case-generator.agent';
import { suspectAgent } from './agents/suspect.agent';
import { gameManagerAgent } from './agents/game-manager.agent';
import { gameMasterAgent } from './agents/game-master.agent';
import { suspectDialogueAgent } from './agents/suspect-dialogue.agent';
import { investigationAgent } from './agents/investigation.agent';
import { evaluationAgent } from './agents/evaluation.agent';

/**
 * Mastra AI 框架配置
 * 集成了赛博侦探游戏的所有AI Agent和工作流
 * 使用DeepSeek AI模型，通过mastra-client调用Agent
 */
export const mastra = new Mastra({
  workflows: {
    weatherWorkflow,
    investigationWorkflow
  },
  agents: {
    weatherAgent,
    caseGeneratorAgent,
    suspectAgent,
    gameManagerAgent,
    gameMasterAgent,
    suspectDialogueAgent,
    investigationAgent,
    evaluationAgent
  },
  storage: new LibSQLStore({
    // 使用文件存储以持久化游戏数据
    url: "file:../mastra.db",
  }),
  logger: new PinoLogger({
    name: 'CyberDetectiveGame',
    level: 'info',
  }),
});

/**
 * 导出游戏管理Agent的便捷调用方法
 */
export {
  callGameManager,
  startNewGame,
  chatWithSuspect,
  submitDeduction,
  getGameStatus
} from './agents/game-manager.agent';
/**
 * 导出便捷的工作流执行函数
 */
export async function executeInvestigationWorkflow(input: any) {
  try {
    const result = await mastra.getWorkflow('investigationWorkflow').execute(input);
    return result;
  } catch (error) {
    console.error('执行调查工作流失败:', error);
    throw error;
  }
}

/**
 * 导出便捷的Agent调用函数
 */
export async function callCaseGeneratorAgent(prompt: string) {
  try {
    const agent = mastra.getAgent('caseGeneratorAgent');
    const response = await agent.streamVNext([{ role: 'user', content: prompt }]);

    let result = '';
    for await (const chunk of response.textStream) {
      result += chunk;
    }

    return {
      content: result,
      toolCalls: response.toolCalls
    };
  } catch (error) {
    console.error('调用案件生成Agent失败:', error);
    throw error;
  }
}

export async function callSuspectAgent(prompt: string) {
  try {
    const agent = mastra.getAgent('suspectAgent');
    const response = await agent.streamVNext([{ role: 'user', content: prompt }]);

    let result = '';
    for await (const chunk of response.textStream) {
      result += chunk;
    }

    return {
      content: result,
      toolCalls: response.toolCalls
    };
  } catch (error) {
    console.error('调用嫌疑人Agent失败:', error);
    throw error;
  }
}
